package org.rc.controller;


import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.rc.dto.CasePageDto;
import org.rc.dto.LawPageDto;
import org.rc.dto.PageDto;
import org.rc.dto.Res;
import org.rc.entity.Law;
import org.rc.service.LawLibraryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/law_library")
public class LawLibraryController {

    @Value("${file.save.path}")
    private String fileSavePath;

    @Autowired
    private LawLibraryService lawLibraryService;

    @PostMapping("/upload")
    public Res uploadFile(@RequestParam("file") MultipartFile file){
        if(null == file){
            return Res.failure("请选择上传到的文档！");
        }
        String fileName = file.getOriginalFilename();
        assert fileName != null;
        if(!fileName.contains(".xls") || !fileName.contains(".xlsx")){
            return Res.failure("请上传excel格式文件");
        }
        String fullFilePath = fileSavePath + File.separator+fileName;
        InputStream inputStream = null;
        try{
            inputStream = file.getInputStream();
            File saveFile = new File(fullFilePath);
            if(saveFile.exists()){
                saveFile.delete();
            }
            FileUtils.copyInputStreamToFile(inputStream,saveFile);
        }catch (Exception e){
            log.error("文件写入磁盘失败，e--->",e);
        }finally {
            if(null != inputStream){
                try{
                    inputStream.close();
                }catch (Exception e){
                    log.error("关闭流失败,e--->",e);
                }

            }
        }
        //全量导入，删除之前入库的数据
        lawLibraryService.removeAllRecords();
        List<Law> laws = new ArrayList<>();
        ExcelReader reader =null;
        try{
            reader = ExcelUtil.getReader(fullFilePath);
            List<Map<String, Object>> sheet = reader.readAll();
            if(CollectionUtils.isEmpty(sheet)){
                return Res.failure("文件内容为空");
            }
            for (Map<String, Object> row : sheet) {
                Law law = new Law();
                if(null!=row.get("罪名")){
                    law.setCharge(String.valueOf(row.get("罪名")).trim());
                }
                if(null!=row.get("法条原文")){
                    law.setLawDetail(String.valueOf(row.get("法条原文")));
                }
                if(null!=row.get("立案标准")){
                    law.setFilingCriteria(String.valueOf(row.get("立案标准")));
                }
                laws.add(law);
            }
            lawLibraryService.addLawLibrary(laws);
        }catch (Exception e){
            log.error("读取excel失败，e--->",e);
            return Res.failure("读取excel失败");
        }finally {
            assert reader != null;
            reader.close();
        }
        return Res.success("数据导入成功");
    }



    @GetMapping("/list")
    public Res getAllLaws(){
        return Res.success(lawLibraryService.getLaws());
    }

    @PostMapping("/page")
    public Res geteCasePage(@RequestBody LawPageDto lawPageDto){
        return Res.success(PageDto.of(lawLibraryService.getLawPage(lawPageDto)));
    }

}
